<template>
  <div>
    <el-dialog
      :title="isEdit ? '编辑' : '提示'"
      :visible="dialogVisible"
      width="50%"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <template>
        <div>
          <el-form
            ref="deptForm"
            :model="form"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="部门名称" prop="name">
              <el-input
                v-model="form.name"
                style="width: 85%"
                placeholder="1-50个字符"
              />
            </el-form-item>
            <el-form-item label="部门编码" prop="code">
              <el-input
                v-model="form.code"
                style="width: 85%"
                placeholder="1-50个字符"
              />
            </el-form-item>
            <el-form-item label="部门负责人" prop="manager">
              <el-select
                v-model="form.manager"
                style="width: 85%"
                placeholder="请选择"
              >
                <!-- label 和 value 两个相同是时 能省略label 只写value -->
                <el-option
                  v-for="obj in employeeList"
                  :key="obj.id"
                  :value="obj.username"
                  :label="obj.username"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="部门介绍" prop="introduce">
              <el-input
                v-model="form.introduce"
                style="width: 85%"
                placeholder="1-300个字符"
                type="textarea"
                :rows="3"
              />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button type="primary" @click="enterFn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEmployeeSimpleAPI,
  addDepartmentsAPI,
  getDepartDetailAPI,
  updateDepartmentsAPI
} from '@/api'
export default {
  props: {
    // 控制弹窗
    dialogVisible: {
      type: Boolean,
      default: false
    },
    parentId: {
      type: String,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    originList: {
      type: Array,
      default: (_) => [],
      require: true
    }
  },
  data() {
    const validCode = (rules, value, callback) => {
      // 点击添加时 映射出 所有的code
      let arr = this.originList.map((item) => item.code)
      if (this.isEdit) {
        // 点击编辑时 先用当前点击的id 过滤出不包含此id的对象 在映射成除去此code的所有code
        arr = this.originList.filter(obj => obj.id !== this.parentId).map(item => item.code)
      }
      arr.includes(value)
        ? callback(new Error(`此部门${value}编码已存在`))
        : callback()
    }
    const validName = (rules, value, callback) => {
      // 点击添加时 先用当前点击的id与所有的pid比较 找到点击部门的下属 映射出下属的所有名字
      let arr = this.originList.filter(obj => obj.pid === this.parentId).map(item => item.name)
      if (this.isEdit) {
        // 点击编辑时 先用当前的id找到 pid
        const obj = this.originList.find(obj => obj.id === this.parentId)
        const pid = obj.pid
        // 用点击的pid 找同级的所有部门 并且除去当前的点击的这个部门 最后映射出 部门名字
        arr = this.originList.filter(obj => obj.pid === pid && obj.id !== this.parentId).map(obj => obj.name)
      }
      arr.includes(value) ? callback(new Error(`此名字 ${value} 已存在`)) : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '部门介绍要求1-300个字符',
            trigger: 'blur'
          }
        ]
      },
      employeeList: []
    }
  },
  watch: {
    dialogVisible() {
      this.getDepartDetailFn()
    }
  },
  created() {
    this.getEmployeeFn()
  },
  methods: {
    async getEmployeeFn() {
      const res = await getEmployeeSimpleAPI()
      this.employeeList = res.data
    },
    async addDepartmentsFn() {
      const res = await addDepartmentsAPI({
        ...this.form,
        pid: this.parentId
      })
      this.$message.success(res.message)
    },
    async getDepartDetailFn() {
      if (this.isEdit) {
        const res = await getDepartDetailAPI(this.parentId)
        this.form = res.data
      }
    },
    async updateDepartmentsFn() {
      const res = await updateDepartmentsAPI({
        ...this.form,
        id: this.parentId
      })
      this.$message.success(res.message)
    },
    // 关闭弹窗(仅限于图标或遮罩)的点击事件
    handleClose(done) {
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     this.$emit('update:dialogVisible', false)
      //     done()
      //   })
      //   .catch(_ => {})
      done()
    },
    // 取消按钮
    cancelFn() {
      this.$emit('update:dialogVisible', false)
    },
    // 确认按钮
    enterFn() {
      this.$refs.deptForm.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.updateDepartmentsFn()
          } else {
            this.addDepartmentsFn()
          }
          this.$emit('update:dialogVisible', false)
          this.$emit('resetEv')
        } else {
          this.$message.error('表单未通过校验')
        }
      })
    }
  }
}
</script>

<style></style>
